package com.cmcc.passenger.data

import com.cmcc.passenger.config.AppConfig
import com.cmcc.passenger.data.entity.AddressBook
import com.cmcc.passenger.data.entity.FavoriteAddress
import com.cmcc.passenger.data.entity.OrderDetail
import com.cmcc.passenger.data.entity.request.*
import com.cmcc.passenger.data.entity.response.*
import com.cmcc.passenger.data.entity.response.CarCategory
import com.cmcc.passenger.data.service.AppApiService
import com.cmcc.passenger.ui.utils.HttpUtil
import com.cmcc.shared.SdkManager
import com.cmcc.shared.model.AppResponse
import com.cmcc.shared.model.DriverCache
import com.cmcc.shared.model.GooglePlace
import com.cmcc.shared.model.MsgBean
import com.cmcc.shared.network.RetrofitRequest
import com.cmcc.shared.network.interceptor.HttpLoggingInterceptor
import com.cmcc.shared.utils.TokenUtils
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import io.reactivex.Observer
import retrofit2.Response
import java.io.File

class AppRequest private constructor() {
    private val apiService: AppApiService = Network.getInstance().appApiService

    private fun getApiService():AppApiService{
        return  RetrofitRequest.Builder().baseUrl(AppConfig.APP_DOMAIN)
            .setLogLevel(HttpLoggingInterceptor.Level.BODY)
            .addHeader("Content-Type","application/json")
            .addHeader("Content-Type","application/json")
            .addHeader("Accept-Language",when (SdkManager.getLanguage()) {
                0 -> "en-US"
                1 -> "zh-CN"
                2 -> "zh-HK"
                else -> "zh-HK"
            })
            .addHeader(
                "Authorization",
//            "Bearer "+SpHelper.getParam(SdkManager.getApplicationContext()!!, SpKeys.USER_TOKEN,""))
                "Bearer "+ TokenUtils.getUserToken()
            )
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
//        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .createService(AppApiService::class.java)
    }


    suspend fun getPassengerInfo(): Response<AppResponse<PassengerInfo>> {
        return getApiService().getPassengerInfo().await()
    }

    /**
     * 创建订单
     * @param order 订单信息
     *
     */
    suspend fun createOrder(order: OrderRecord?): Response<AppResponse<CreateOrderResponse>> {
        return getApiService().createOrder(order).await()
    }

    /**
     * 查询正在进行的订单
     */
    suspend fun queryOrderInProgress(): Response<AppResponse<OrderRecord>> {
        return getApiService().queryOrderInProgress(1).await()
    }

    suspend fun getRemarks():Response<AppResponse<List<Remark>>>{
        return getApiService().getRemarks().await()
    }

    /**
     * 获取隧道列表
     */
    suspend fun getTunnel(): Response<AppResponse<List<Tunnel>>> {
        return getApiService().getTunnel().await()
    }

    /**
     * 获取小费列表
     */
    suspend fun getGratuity(): Response<AppResponse<List<Gratuity>>> {
        return getApiService().getGratuity().await()
    }

    /**
     * 更新小费
     * @param orderId 需要更新小费的订单id
     * @param amount 更新小费数值
     */
    suspend fun updateBounty(orderId: String, amount: String): Response<AppResponse<Boolean>> {
        return getApiService().updateBounty(orderId , amount).await()
    }

    /**
     * 获取车辆类型列表
     */
    suspend fun getCarCategory(): Response<AppResponse<List<CarCategory>>> {
        return getApiService().getCarCategory().await()
    }

    /**
     * 获取更多出行列表，其中包括车辆类型列表，小费列表，隧道列表
     */
    suspend fun getTravelItemList(): Response<AppResponse<TravelItem>> {
        return getApiService().getTravelItemList().await()
    }

    /**
     * 获取车辆类型列表
     */
    suspend fun getVehicles(): Response<AppResponse<List<CarCategory>>> {
        return getApiService().getVehicles().await()
    }

    /**
     * 获取隧道列表
     */
    suspend fun getTunnels(): Response<AppResponse<List<Tunnel>>> {
        return getApiService().getTunnels().await()
    }

    /**
     * 查询附近的车辆
     */
    suspend fun nearbyCar(
        lat: Double,
        lng: Double,
        range: Int = 100
    ): Response<AppResponse<List<NearbyCar>>> {
        return getApiService().nearbyDriver(lat, lng, range).await()
    }

    /**
     * 获取用户常用地址
     */
    suspend fun getAddress(): Response<AppResponse<AddressBook>> {
        return getApiService().getAddress().await()
    }

    /**
     * 添加用户常用地址
     */
    suspend fun addAddress(address: FavoriteAddress): Response<AppResponse<String>> {
        return getApiService().addAddress(address).await()
    }

    /**
     * 删除用户常用地址
     */
    suspend fun deleteAddress(id: String): Response<AppResponse<String>> {
        return getApiService().deleteAddress(id).await()
    }

    /**
     * 获取订单列表
     * @param page current page
     * @param pageSize 一次请求的数据项
     *
     *
     */
    suspend fun getOrders(
        page: Int,
        pageSize: Int,
        role: Int = 1,
        status: Int? = null
    ): Response<AppResponse<OrderRecordResponse>> {
        return getApiService().getOrderRecords(page, pageSize, role, status).await()
    }

    /**
     * 取消订单，放弃叫车
     * @param id order id
     */
    suspend fun cancelOrder(id: String): Response<AppResponse<String>> {
        return getApiService().cancelCall(id).await()
    }

    /**
     * 获取订单模板
     * @param id order template id
     */
    suspend fun getOrderTemplate(id: String): Response<AppResponse<OrderTemplate>> {
        return getApiService().getOrderTemplate(id).await()
    }

    /**
     * 获取订单详情
     * @param id 订单id
     */
    suspend fun getOrderDetail(id: String): Response<AppResponse<OrderDetail>> {
        return getApiService().getOrderDetail(id).await()
    }

    /**
     * 乘客确认司机已经到达
     * @param id order id
     */
    suspend fun arrivePassengerConfirm(id: String): Response<AppResponse<String>> {
        return getApiService().arrivePassengerConfirm(id).await()
    }

    /**
     * CALL台放弃叫车
     * @param id order id
     * @param remark 取消备注
     */
    suspend fun cancelOrder(id: String, remark: String): Response<AppResponse<String>> {
        return getApiService().cancelOrder(id, remark).await()
    }

    /**
     * 放弃叫车
     * @param id order id
     * @param remark 取消备注
     */
    suspend fun cancelCall(id: String, remark: String): Response<AppResponse<String>> {
        return getApiService().cancelCall(id, remark).await()
    }

    suspend fun getDriverCache(id: String): Response<AppResponse<DriverCache>> {
        return getApiService().getDriverCache(id).await()
    }

    /**
     * 根据文本内容查找地点
     */
    fun findPlaceFromText(text: String, observer: Observer<GooglePlace>) {
        val fields = "photos,formatted_address,name,rating,opening_hours,geometry"
        //        RxUtil.subscribe(googleApiService.findPlaceFromText(text,"textquery",fields,"AIzaSyB2Vk0-GyBzSboclVAECQw8QuptIHYUe40"),observer);


    }


    suspend fun computationFee(
        mileage: Double,
        tunnelCode: String,
        vehicleTypeCode: String
    ): Response<AppResponse<OrderFee>> {
        var request = RequestFee(mileage, tunnelCode, vehicleTypeCode)
        return getApiService().computationFee(request).await()
    }


    /**
     * 构建单例对象
     */
    companion object {
        @Volatile
        private var instance: AppRequest? = null

        fun getInstance(): AppRequest {
            return instance ?: synchronized(this) {
                instance ?: AppRequest().also { instance = it }
            }
        }
    }

    /**
     * 消息列表
     */
    suspend fun list( pageNum: Int, pageSize: Int): Response<AppResponse<MsgBean>> {
        return getApiService().list(pageNum,pageSize).await()
    }



    /**
     * 查询当前司机信息
     */
    suspend fun info( ): Response<AppResponse<DiverInfo>> {
        return getApiService().info().await()
    }

    /**
     * 一键上传
     */
    suspend fun upload(file:File, mediaType:String ): Response<AppResponse<String>> {
        return getApiService().upload(HttpUtil.filesToMultipartBody(null, file, mediaType)).await()
    }

    /**
     * 评价接口
     */
    suspend fun evaluate( request: EvaluateRequest): Response<AppResponse<String>> {
        return getApiService().evaluate(request).await()
    }

    /**
     * 注册
     */
    suspend fun register( request: RegistRequest): Response<AppResponse<String>> {
        return getApiService().register(request).await()
    }

    /**
     * 獲取驗證碼
     */
    suspend fun code( request: CodeRequest): Response<AppResponse<String>> {
        val map = mapOf<String, String>("phone" to request.phone )
        return getApiService().code(map).await()
    }


}
